{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c4cc7e22",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2 as cv\n",
    "\n",
    "im = np.zeros((300,300,3),np.uint8)\n",
    "im[100:200,100:200] = 255\n",
    "#颜色空间转换成灰度图\n",
    "imgray = cv.cvtColor(im,cv.COLOR_BGR2GRAY)\n",
    "#通过二值化处理取得二值图\n",
    "ret, thresh = cv.threshold(imgray, 127, 255, 0)\n",
    "\n",
    "retrievalMode = cv.RETR_TREE\n",
    "approxMethod = cv.CHAIN_APPROX_NONE\n",
    "contours,hieraechy = cv.findContours(thresh, retrievalMode, approxMethod)\n",
    "\n",
    "#draw contours\n",
    "img = np.zeros((300,300,3), np.uint8)\n",
    "contoursIdx = 0\n",
    "color,thickness = (0,0,255), 1\n",
    "cv.drawContours(img, contours, contoursIdx, color, thickness)   #标记轮廓\n",
    "\n",
    "cv.imshow(\"im\", im)\n",
    "cv.imshow(\"img\", img)\n",
    "cv.waitKey(0)\n",
    "# cv.destroyAllWindows()\n",
    "\n",
    "#draw contours via using pt \n",
    "img2 = np.zeros((300,300,3), np.uint8)\n",
    "cnt = contours[0]\n",
    "\n",
    "#轮廓数组\n",
    "for pt in cnt:\n",
    "    cv.line(img2, pt[0], pt[0], \n",
    "            color,thickness)\n",
    "\n",
    "cv.imshow(\"img2\", img2)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cedce367",
   "metadata": {},
   "outputs": [],
   "source": [
    "#采用近似方法说明\n",
    "import numpy as np\n",
    "import cv2 as cv\n",
    "\n",
    "im = np.zeros((300,300,3), np.uint8)\n",
    "im[100:200,100:200] = 255\n",
    "imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)\n",
    "\n",
    "ret, thresh = cv.threshold(imgray, 127, 255, 0)\n",
    "\n",
    "retrievalMode = cv.RETR_TREE\n",
    "approxMethod = cv.CHAIN_APPROX_SIMPLE\n",
    "contours, hierarchy = cv.findContours(thresh, retrievalMode, approxMethod)\n",
    "\n",
    "#draw contours\n",
    "img2 = np.zeros((300,300,3), np.uint8)\n",
    "cnt = contours[0]\n",
    "\n",
    "radius = 2\n",
    "color,thickness = (0,0,255), 1\n",
    "for pt in cnt:\n",
    "    center = pt[0]\n",
    "    cv.circle(img2, center, radius, \n",
    "            color,thickness)\n",
    "cv.imshow(\"im\", im)\n",
    "cv.imshow(\"img2\", img2)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31dc2709",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
